<template>
  <div class="photo-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="媒体类型">
          <el-radio-group v-model="searchForm.type" @change="handleTypeChange">
            <el-radio-button :label="MediaType.PHOTO">图片</el-radio-button>
            <el-radio-button :label="MediaType.VIDEO">视频</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文件名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入文件名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.activityType" placeholder="请选择活动类型" clearable style="width: 150px">
            <el-option label="全部类型" :value="ActivityType.ALL" />
            <el-option label="精彩回顾" :value="ActivityType.REVIEW" />
            <el-option label="新品发布" :value="ActivityType.PRODUCT" />
            <el-option label="会议现场" :value="ActivityType.MEETING" />
            <el-option label="嘉宾专访" :value="ActivityType.INTERVIEW" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 媒体列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">照片列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>上传文件
            </el-button>
            <el-tooltip :content="selectedPhotos.length ? '下载选中的文件' : '请先选择要下载的文件'" placement="top">
              <el-button
                type="warning"
                :disabled="!selectedPhotos.length"
                @click="handleBatchDownload"
              >
                <el-icon><Download /></el-icon>
                批量下载 {{ selectedPhotos.length ? `(${selectedPhotos.length})` : '' }}
              </el-button>
            </el-tooltip>
            <el-tooltip :content="selectedPhotos.length ? '删除选中的文件' : '请先选择要删除的文件'" placement="top">
              <el-button 
                type="danger" 
                :disabled="!selectedPhotos.length"
                @click="handleBatchDelete"
              >
                <el-icon><Delete /></el-icon>
                批量删除 {{ selectedPhotos.length ? `(${selectedPhotos.length})` : '' }}
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>
      <el-table 
        :data="mediaList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="照片预览" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.type === MediaType.PHOTO"
              :src="row.url"
              :preview-src-list="[row.url]"
              fit="cover"
              style="width: 80px; height: 80px"
            />
            <el-icon v-else class="video-icon"><VideoCamera /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            {{ row.type === MediaType.PHOTO ? '图片' : '视频' }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="activityType" label="活动类型" width="120">
          <template #default="{ row }">
            {{ getActivityTypeLabel(row.activityType) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handleDownload(row)">
              下载
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑媒体对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '上传文件' : '编辑文件'"
      width="500px"
    >
      <el-form
        ref="mediaFormRef"
        :model="mediaForm"
        :rules="mediaRules"
        label-width="100px"
      >
        <el-form-item label="媒体类型" prop="type">
          <el-radio-group v-model="mediaForm.type">
            <el-radio :label="MediaType.PHOTO">图片</el-radio>
            <el-radio :label="MediaType.VIDEO">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文件名称" prop="name">
          <el-input v-model="mediaForm.name" placeholder="请输入文件名称" />
        </el-form-item>

        <el-form-item label="文件描述" prop="description">
          <el-input
            v-model="mediaForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入文件描述"
          />
        </el-form-item>

        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="mediaForm.activityType" placeholder="请选择活动类型" style="width: 100%">
            <el-option label="精彩回顾" :value="ActivityType.REVIEW" />
            <el-option label="新品发布" :value="ActivityType.PRODUCT" />
            <el-option label="会议现场" :value="ActivityType.MEETING" />
            <el-option label="嘉宾专访" :value="ActivityType.INTERVIEW" />
          </el-select>
        </el-form-item>

        <el-form-item label="上传文件" prop="file">
          <el-upload
            class="media-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :accept="mediaForm.type === MediaType.PHOTO ? 'image/*' : 'video/*'"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <template #default>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                {{ mediaForm.type === MediaType.PHOTO ? '只能上传jpg/png图片文件' : '只能上传mp4视频文件' }}
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { Plus, Delete, VideoCamera, Download, Search, Refresh } from '@element-plus/icons-vue'
import { 
  MediaType, 
  ActivityType, 
  getMediaList, 
  addMedia, 
  updateMedia, 
  deleteMedia, 
  uploadMediaFile,
  batchDeleteMedia,
  batchDownloadMedia,
} from '@/api/photo'
import type { Media } from '@/api/photo'

interface ExtendedUploadFile extends UploadFile {
  type?: string
}

// 定义文件类型枚举
enum FileType {
  ALL = 'ALL',
  MEETING = 'MEETING',
  GENERAL = 'GENERAL'
}

// 搜索表单
const searchForm = reactive({
  name: '',
  type: MediaType.PHOTO,
  activityType: ActivityType.ALL
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const mediaFormRef = ref<FormInstance>()
const submitting = ref(false)

const mediaForm = reactive({
  id: '',
  name: '',
  description: '',
  type: MediaType.PHOTO,
  activityType: ActivityType.REVIEW,
  file: null as File | null
})

// 表单校验规则
const mediaRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入文件描述', trigger: 'blur' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }]
})

const loading = ref(false)
const mediaList = ref<Media[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedPhotos = ref<Media[]>([])
const previewVisible = ref(false)
const previewUrl = ref('')

// 获取活动类型标签
const getActivityTypeLabel = (type: ActivityType) => {
  const labels = {
    [ActivityType.ALL]: '全部类型',
    [ActivityType.REVIEW]: '精彩回顾',
    [ActivityType.PRODUCT]: '新品发布',
    [ActivityType.MEETING]: '会议现场',
    [ActivityType.INTERVIEW]: '嘉宾专访'
  }
  return labels[type]
}

// 获取媒体列表
const fetchMediaList = async () => {
  loading.value = true
  try {
    const response = await getMediaList({
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      type: searchForm.type,
      activityType: searchForm.activityType
    })
    mediaList.value = response.current_data
    total.value = response.total_record
  } catch (error) {
    console.error('获取媒体列表失败:', error)
    ElMessage.error('获取媒体列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchMediaList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = MediaType.PHOTO
  searchForm.activityType = ActivityType.ALL
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchMediaList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchMediaList()
}

// 文件上传处理
const handleFileChange = (file: any) => {
  mediaForm.file = file.raw
}

const handleFileRemove = () => {
  mediaForm.file = null
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(mediaForm, {
    id: '',
    name: '',
    description: '',
    type: MediaType.PHOTO,
    activityType: ActivityType.REVIEW,
    file: null
  })
  dialogVisible.value = true
}

// 编辑媒体
const handleEdit = (row: Media) => {
  dialogType.value = 'edit'
  Object.assign(mediaForm, {
    ...row,
    id: row.id.toString()
  })
  dialogVisible.value = true
}

// 删除媒体
const handleDelete = async (row: Media) => {
  try {
    await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      type: 'warning'
    })
    await deleteMedia(row.id.toString())
    ElMessage.success('删除成功')
    fetchMediaList()
  } catch (error) {
    console.error('删除文件失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!mediaFormRef.value) return
  await mediaFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        submitting.value = true
        
        if (dialogType.value === 'add') {
          if (!mediaForm.file) {
            ElMessage.error('请选择要上传的文件')
            return
          }

          // 1. 先上传文件获取URL
          const fileResponse = await uploadMediaFile(mediaForm.file)
          const fileUrl = fileResponse.data

          // 2. 构建媒体数据
          const mediaData: Partial<Media> = {
            name: mediaForm.name,
            description: mediaForm.description,
            type: mediaForm.type,
            activityType: mediaForm.activityType,
            url: fileUrl
          }

          // 3. 添加媒体记录
          await addMedia(mediaData)
          ElMessage.success('添加成功')
        } else {
          // 如果是编辑且上传了新文件
          if (mediaForm.file) {
            // 上传新文件获取新的URL
            const fileResponse = await uploadMediaFile(mediaForm.file)
            const fileUrl = fileResponse.data
            
            // 更新媒体数据包含新的URL
            await updateMedia(mediaForm.id, {
              name: mediaForm.name,
              description: mediaForm.description,
              type: mediaForm.type,
              activityType: mediaForm.activityType,
              url: fileUrl
            })
          } else {
            // 如果只是更新其他信息，不更新文件
            await updateMedia(mediaForm.id, {
              name: mediaForm.name,
              description: mediaForm.description,
              type: mediaForm.type,
              activityType: mediaForm.activityType
            })
          }
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchMediaList()
      } catch (error) {
        console.error('提交文件失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 媒体类型变化处理
const handleTypeChange = () => {
  currentPage.value = 1
  fetchMediaList()
}

// 表格选择处理
const handleSelectionChange = (selection: Media[]) => {
  selectedPhotos.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedPhotos.value.length) {
    ElMessage.warning('请选择要删除的文件')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的文件吗？', '提示', {
      type: 'warning'
    })
    await batchDeleteMedia(selectedPhotos.value.map((photo: Media) => photo.id))
    ElMessage.success('批量删除成功')
    fetchMediaList()
  } catch (error) {
    console.error('批量删除文件失败:', error)
  }
}

// 批量下载
const handleBatchDownload = async () => {
  if (!selectedPhotos.value.length) {
    ElMessage.warning('请选择要下载的文件')
    return
  }
  try {
    loading.value = true
    const downloadResponse = await batchDownloadMedia(selectedPhotos.value.map(photo => photo.id))
    const downloadBlob = new Blob([downloadResponse.data])
    const downloadUrl = window.URL.createObjectURL(downloadBlob)
    const downloadLink = document.createElement('a')
    downloadLink.href = downloadUrl
    downloadLink.download = '媒体文件.zip'
    document.body.appendChild(downloadLink)
    downloadLink.click()
    document.body.removeChild(downloadLink)
    window.URL.revokeObjectURL(downloadUrl)
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败')
  } finally {
    loading.value = false
  }
}

// 下载处理
const handleDownload = (row: Media) => {
  if (!row.url) {
    ElMessage.warning('文件链接不存在')
    return
  }
  window.open(row.url, '_blank')
}

onMounted(() => {
  fetchMediaList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.photo-management {
  .video-icon {
    font-size: 40px;
    color: #409eff;
  }

  .media-upload {
    :deep(.el-upload-list) {
      max-height: 150px;
      overflow-y: auto;
    }

    :deep(.el-upload-dragger) {
      width: 100%;
      height: 180px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 8px;

      .el-icon--upload {
        font-size: 48px;
        color: #409eff;
        margin-bottom: 0;
      }

      .el-upload__text {
        font-size: 14px;
        color: #606266;

        em {
          color: #409eff;
          font-style: normal;
        }
      }
    }

    :deep(.el-upload--picture-card) {
      --el-upload-picture-card-size: 120px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
        color: #409eff;
      }
    }

    :deep(.el-upload-list__item) {
      border-radius: 8px;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }
}
</style> 